package page

import (
	"fmt"
	"reflect"
)

func SetPageParams(pageSize, pageIndex *int64, defaultPageSize int64) {
	SetIntDefault(pageSize, defaultPageSize)
	SetIntDefault(pageIndex, 1)
}

func SetIntDefault(num *int64, defaultNum int64) {
	if *num <= 0 {
		*num = defaultNum
	}
}

func Search(params Params, s interface{}) PageResult {
	SetPageParams(&params.PageSize, &params.PageIndex, 20)
	if reflect.TypeOf(s).Kind() != reflect.Ptr {
		panic("input is not ptr")
	}
	if reflect.ValueOf(s).Elem().Kind() != reflect.Slice {
		fmt.Println(reflect.ValueOf(s).Elem().Kind())
		panic("input is not slice:")
	}
	v := reflect.ValueOf(s).Elem()
	min := int(params.PageSize * (params.PageIndex - 1))
	max := int(params.PageSize * params.PageIndex)
	total := v.Len()
	if min > v.Len()-1 {
		v.SetLen(0)
	} else if max > v.Len() {
		v.Set(v.Slice(min, v.Len()))
	} else {
		v.Set(v.Slice(min, max))
	}
	return PageResult{
		PageSize:    params.PageSize,
		PageIndex:   params.PageIndex,
		TotalNumber: int64(total),
		TotalPage:   GetTotalPages(int64(total), params.PageSize),
	}
}
